package com.zt.rongda.workbill.service;

import java.util.Date;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zt.rongda.constant.BusConstant;
import com.zt.rongda.employee.inter.EmployeeMapper;
import com.zt.rongda.order.inter.OrderItemMapper;
import com.zt.rongda.order.model.OrderItem;
import com.zt.rongda.workbill.inter.WorkbillTaskFileMapper;
import com.zt.rongda.workbill.inter.WorkbillTaskMapper;
import com.zt.rongda.workbill.inter.WorkbillTaskWorkerMapper;
import com.zt.rongda.workbill.model.WorkbillTask;
import com.zt.rongda.workbill.model.WorkbillTaskFile;
import com.zt.rongda.workbill.model.WorkbillTaskWorker;
import com.zt.servlet.ReqBean;
import com.zt.system.model.BusinessException;
import com.zt.system.model.SqlBuilder;
import com.zt.system.service.BaseService;
import com.zt.util.StringUtil;

@Service
public class WorkbillTaskService extends BaseService{

    @Autowired
    private WorkbillTaskMapper workbillTaskMapper;
    
    @Autowired
    private WorkbillTaskWorkerMapper workbillTaskWorkerMapper;
    
    @Autowired
    private WorkbillTaskFileMapper workbillTaskFileMapper;
    
    @Autowired
    private OrderItemMapper orderItemMapper;
    
    @Autowired
    private EmployeeMapper employeeMapper;

    /**
    * 查询
    *
    * @param reqBean
    * @return
    */
    public JSONObject getTable(ReqBean reqBean) {
        SqlBuilder sql = new SqlBuilder("select t.TASK_ID,t.C_TASK_TYPE,t.WORKBILL_ID,t.WORKBILL_ITEM_ID,t.OWNER,t.WORK_GROUP_ID,t.START_TIME,t.LIMIT_TIME,t.END_TIME,t.COMMENT,t.STATUS,");
        sql.appendSql(" e1.EMP_NAME caituEmpName,e2.EMP_NAME printEmpName,e3.EMP_NAME fumoEmpName,");
        sql.appendSql(" e.EMP_NAME,g.GROUP_NAME ,");
        sql.appendSql(" oi.* from AD_WORKBILL_TASK t ");
        sql.appendSql(" inner join AD_WORKBILL w on t.WORKBILL_ID = w.WORKBILL_ID");
        sql.appendSql(" left join AD_ORDER_ITEM oi on t.ORDER_ITEM_ID = oi.ORDER_ITEM_ID ");
        sql.appendSql(" left join AD_ORDER o on oi.ORDER_ID = o.ORDER_ID ");
        sql.appendSql(" left join EMPLOYEE e on t.OWNER = e.EMP_ID ");
        sql.appendSql(" left join EMPLOYEE_GROUP g on t.WORK_GROUP_ID = g.GROUP_ID ");
        sql.appendSql(" left join EMPLOYEE e1 on oi.CAITU_EMP_ID = e1.EMP_ID ");
        sql.appendSql(" left join EMPLOYEE e2 on oi.PRINT_EMP_ID = e2.EMP_ID ");
        sql.appendSql(" left join EMPLOYEE e3 on oi.FUMO_EMP_ID = e3.EMP_ID ");
        sql.appendSql(" where 1 = 1 ");
        sql.addWhere(" t.WORKBILL_ITEM_ID", reqBean.getInfo("workbillItemId"));
        sql.addWhere(" w.WORKBILL_ID", reqBean.getInfo("workbillId"));
        sql.addWhere(" o.ORDER_ID", reqBean.getInfo("orderId"));
        sql.addWhere(" t.C_TASK_TYPE", reqBean.getInfo("taskType"));
        sql.addWhere(" w.C_WORKBILL_TYPE", reqBean.getInfo("workbillType"));
        sql.addWhere(" o.C_ORDER_TYPE", reqBean.getInfo("orderType"));
        sql.addWhere(" o.CUSTOMER_ID", reqBean.getInfo("customerId"));
        sql.addWhere(" t.OWNER", reqBean.getInfo("owner"));
        sql.addWhere(" t.WORK_GROUP_ID", reqBean.getInfo("workGroupId"));
        sql.addWhere(" t.STATUS", reqBean.getInfo("status"));
        
        JSONObject result = queryTable(sql, reqBean.getPageSize(), reqBean.getPageIndex());
        if(result != null){
            JSONArray rows = result.getJSONArray("rows");
            for(Object o : rows){
                JSONObject task = (JSONObject)o;
                task.put("workers", getWorkersOfTask(task.optString("taskId")));
                task.put("files", getFilesOfTask(task.optString("taskId")));
                
            }
        }
        return result;
    }
    
    /**
     * 查询工单任务
     * @param workbillId
     * @return
     */
    public JSONArray getWorkbillTasks(String workbillId){
        StringBuffer sql = new StringBuffer("select t.*, e.EMP_NAME, g.GROUP_NAME from AD_WORKBILL_TASK t ");
        sql.append(" left join EMPLOYEE e on t.OWNER = e.EMP_ID ");
        sql.append(" left join EMPLOYEE_GROUP g on t.WORK_GROUP_ID = g.GROUP_ID ");
        sql.append(" where t.WORKBILL_ID = ?");
        JSONArray tasks = query(sql.toString(), workbillId);
        if(tasks != null){
            for(Object o : tasks){
                JSONObject task = (JSONObject)o;
                String taskId = task.optString("taskId");
                task.put("workers", getWorkersOfTask(taskId));
                task.put("files", getFilesOfTask(taskId));
            }
        }
        return tasks;
    }
    
    /**
     * 明细任务
     * @param orderItemId
     * @return
     */
    public JSONArray getOrderItemTasks(String orderItemId){
        StringBuffer sql = new StringBuffer("select t.*, e.EMP_NAME, g.GROUP_NAME from AD_WORKBILL_TASK t ");
        sql.append(" left join EMPLOYEE e on t.OWNER = e.EMP_ID ");
        sql.append(" left join EMPLOYEE_GROUP g on t.WORK_GROUP_ID = g.GROUP_ID ");
        sql.append(" where t.ORDER_ITEM_ID = ?");
        JSONArray tasks = query(sql.toString(), orderItemId);
        if(tasks != null){
            for(Object o : tasks){
                JSONObject task = (JSONObject)o;
                String taskId = task.optString("taskId");
                task.put("workers", getWorkersOfTask(taskId));
                task.put("files", getFilesOfTask(taskId));
            }
        }
        return tasks;
    }
    /**
    * 通过id查询
    *
    * @param taskId
    * @return
    */
    public WorkbillTask getById(String taskId) {
        return workbillTaskMapper.selectByPrimaryKey(taskId);
    }
    
    /**
     * 查询任务办理人
     * 
     * @param taskId
     * @return
     */
    public JSONArray getWorkersOfTask(String taskId) {
        SqlBuilder sql = new SqlBuilder("select w.*,e.EMP_NAME from AD_WORKBILL_TASK_WORKER w");
        sql.appendSql(" left join EMPLOYEE e on w.EMP_ID = e.EMP_ID");
        sql.appendSql(" where w.TASK_ID = ?", taskId);
        return query(sql);
    }

    /**
     * 查询任务附件
     * 
     * @param taskId
     * @return
     */
    public JSONArray getFilesOfTask(String taskId) {
        SqlBuilder sql = new SqlBuilder("select * from AD_WORKBILL_TASK_FILE where TASK_ID = '" + taskId + "'");
        sql.orderBy(" order by MAKE_TIME");
        return query(sql);
    }
    
    /**
     * 查询任务办理人
     * 
     * @param taskId
     * @return
     */
    public void completeTask(ReqBean reqBean) {
       String taskId = reqBean.getInfo("taskId");
       if(StringUtil.isEmpty(taskId)){
           throw new BusinessException("参数为空");
       }
       WorkbillTask task = workbillTaskMapper.selectByPrimaryKey(taskId);
       if(task == null || BusConstant.Task.STATUS_COMPLETE.equals(task.getStatus())){
           throw new BusinessException("任务不存在或已完成!");
       }
       
       Date now = new Date();
       
       String filesStr = reqBean.getInfo("files");
       if(StringUtil.isNotEmpty(filesStr)){
           JSONArray files = JSONArray.fromObject(filesStr);
           if(files != null){
               for(Object o : files){
                   JSONObject JSONFile = (JSONObject)o;
                   WorkbillTaskFile file = new WorkbillTaskFile();
                   file.setFileId(stringId());
                   file.setTaskId(taskId);
                   file.setFileName(JSONFile.optString("name"));
                   file.setFilePath(JSONFile.optString("path"));
                   file.setOperator(reqBean.getUserId());
                   file.setMakeTime(now);
                   workbillTaskFileMapper.insert(file);
               }
           }
       }
       
       task.setEndTime(now);
       task.setComment(reqBean.getInfo("comment"));
       task.setStatus(BusConstant.Task.STATUS_COMPLETE);
       task.setModifyTime(now);
       workbillTaskMapper.updateByPrimaryKeySelective(task);
       
       
       if(BusConstant.TaskType.TASK_TYPE_CAITU.equals(task.getTaskType())){
           String orderItemId = task.getOrderItemId();
           OrderItem orderItem = orderItemMapper.selectByPrimaryKey(orderItemId);
           
           String caituArea = reqBean.getInfo("caituArea");
           orderItem.setCaituArea(Double.valueOf(StringUtil.isEmpty(caituArea) ? "0" : caituArea));
           orderItem.setCaituEmpId(task.getOwner());
           orderItem.setCaituDate(now);
           
           orderItemMapper.updateByPrimaryKeySelective(orderItem);
           
           WorkbillTaskWorker worker = new WorkbillTaskWorker();
           worker.setTaskId(taskId);
           worker.setEmpId(task.getOwner());
           workbillTaskWorkerMapper.insert(worker);
       }else if(BusConstant.TaskType.TASK_TYPE_PRINT.equals(task.getTaskType())){
           String orderItemId = task.getOrderItemId();
           OrderItem orderItem = orderItemMapper.selectByPrimaryKey(orderItemId);
           
           orderItem.setPrintMachineNo(reqBean.getInfo("printMachineNo"));
           orderItem.setPrintAccuracy(reqBean.getInfo("printAccuracy"));
           orderItem.setPrintEmpId(task.getOwner());
           orderItem.setPrintDate(now);
           
           orderItemMapper.updateByPrimaryKeySelective(orderItem);
           
           WorkbillTaskWorker worker = new WorkbillTaskWorker();
           worker.setTaskId(taskId);
           worker.setEmpId(task.getOwner());
           workbillTaskWorkerMapper.insert(worker);
       }else if(BusConstant.TaskType.TASK_TYPE_FUMO.equals(task.getTaskType())){
           String orderItemId = task.getOrderItemId();
           OrderItem orderItem = orderItemMapper.selectByPrimaryKey(orderItemId);
          
           orderItem.setFumoEmpId(task.getOwner());
           orderItem.setFumoDate(now);
          
           orderItemMapper.updateByPrimaryKeySelective(orderItem);
           
           WorkbillTaskWorker worker = new WorkbillTaskWorker();
           worker.setTaskId(taskId);
           worker.setEmpId(task.getOwner());
           workbillTaskWorkerMapper.insert(worker);
       }else if(BusConstant.TaskType.TASK_TYPE_PUBLISH.equals(task.getTaskType())){
           String empIdsStr = reqBean.getInfo("empIds");
           if(!StringUtil.isEmpty(empIdsStr)){
               JSONArray empIds = JSONArray.fromObject(empIdsStr);
               if(empIds != null && !empIds.isEmpty()){
                   for(Object o : empIds){
                       String empId = (String)o;
                       WorkbillTaskWorker worker = new WorkbillTaskWorker();
                       worker.setTaskId(taskId);
                       worker.setEmpId(empId);
                       workbillTaskWorkerMapper.insert(worker);
                   }
               }
           }
           
       }
       
    }

}